<template>
  <div class="user-center">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>个人中心</span>
        </div>
      </template>
      
      <div class="user-center-content">
        <!-- 用户基本信息 -->
        <div class="user-info-section">
          <div class="user-avatar">
            <img :src="userInfo.avatar || 'https://img2.baidu.com/it/u=3422222422,2222222222&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500'" alt="用户头像" class="avatar" />
            <!-- <el-button type="primary" @click="uploadAvatar" size="small">更换头像</el-button> -->
            <input type="file" ref="avatarInput" style="display: none;" accept="image/*" @change="handleAvatarUpload">
          </div>
          
          <div class="user-basic-info">
            <h3>{{ userInfo.name || '未设置' }}</h3>
            <p class="user-id">用户ID：{{ userInfo.id }}</p>
            <p class="user-join-time">加入时间：{{ userInfo.joinTime || '未知' }}</p>
            <p class="user-level">用户等级：{{ userLevel }}</p>
          </div>
          
          <div class="user-stats">
            <div class="stat-item">
              <div class="stat-value">{{ myActivities.length }}</div>
              <div class="stat-label">已参加活动</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ myTopics.length }}</div>
              <div class="stat-label">发布话题</div>
            </div>
            <!-- <div class="stat-item">
              <div class="stat-value">{{ myReplies.length }}</div>
              <div class="stat-label">回复数量</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ userPoints }}</div>
              <div class="stat-label">积分</div>
            </div> -->
          </div>
        </div>
        
        <!-- 个人信息编辑 -->
        <div class="user-edit-section">
          <el-tabs v-model="activeTab">
            <el-tab-pane label="基本信息" name="basic-info">
              <el-form ref="basicInfoFormRef" :model="userInfo" :rules="basicInfoRules" label-width="120px" style="max-width: 600px;">
                <el-form-item label="昵称" prop="nickName">
                  <el-input v-model="userInfo.nickName" placeholder="请输入昵称"></el-input>
                </el-form-item>
                <el-form-item label="性别" prop="sexy" :rules="[{ required: true, message: '请选择性别', trigger: 'blur' }]">
                  <el-radio-group v-model="userInfo.sexy">
                    <el-radio label="male">男</el-radio>
                    <el-radio label="female">女</el-radio>
                    <el-radio label="secret">保密</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="年龄" prop="age" :rules="[{ required: true, message: '请输入年龄', trigger: 'blur' }]">
                  <el-input v-model.number="userInfo.age" type="number" placeholder="请输入年龄"></el-input>
                </el-form-item>
                <el-form-item label="联系电话" prop="phoneNo" :rules="[{ required: true, message: '请输入联系电话', trigger: 'blur' }]">
                  <el-input v-model="userInfo.phoneNo" placeholder="请输入联系电话"></el-input>
                </el-form-item>
                <el-form-item label="电子邮箱" prop="email" :rules="[{ required: true, message: '请输入电子邮箱', trigger: 'blur' }]">
                  <el-input v-model="userInfo.email" placeholder="请输入电子邮箱"></el-input>
                </el-form-item>
                <el-form-item label="所在城市" prop="city" :rules="[{ required: true, message: '请输入所在城市', trigger: 'blur' }]">
                  <el-input v-model="userInfo.city" placeholder="请输入所在城市"></el-input>
                </el-form-item>
                <el-form-item label="个人简介" prop="bio" :rules="[{ required: true, message: '请输入个人简介', trigger: 'blur' }]">
                  <el-input v-model="userInfo.bio" type="textarea" placeholder="请输入个人简介"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="saveBasicInfo" :loading="savingBasicInfo">保存修改</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            
            <el-tab-pane label="我的活动" name="my-activities">
              <el-table :data="myActivities" style="width: 100%">
                <el-table-column prop="name" label="活动名称" width="300"></el-table-column>
                <el-table-column prop="time" label="活动时间"></el-table-column>
                <el-table-column prop="location" label="活动地点"></el-table-column>
                <el-table-column prop="status" label="参与状态">
                  <template #default="scope">
                    <el-tag :type="getActivityStatusType(scope.row.status)">{{ scope.row.statusText }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="120" fixed="right">
                  <template #default="scope">
                    <el-button 
                      v-if="scope.row.status === 'pending'" 
                      type="danger" 
                      size="small" 
                      @click="cancelActivity(scope.row.id)"
                    >
                      取消
                    </el-button>
                    <el-button 
                      v-else-if="scope.row.status === 'participated' || scope.row.status === 'completed'"
                      type="primary" 
                      size="small" 
                      @click="viewActivityDetail(scope.row.id)"
                    >
                      详情
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            
            <el-tab-pane label="我的话题" name="my-topics">
              <el-table :data="myTopics" style="width: 100%">
                <el-table-column prop="title" label="话题标题" width="400" fixed>
                  <template #default="scope">
                    <router-link :to="'/front/forum/' + scope.row.id" class="topic-title">{{ scope.row.title }}</router-link>
                  </template>
                </el-table-column>
                <el-table-column prop="category" label="分类" width="120">
                  <template #default="scope">
                    <el-tag :type="getTopicCategoryType(scope.row.category)">{{ getTopicCategoryText(scope.row.category) }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="createTime" label="发布时间" width="160"></el-table-column>
                <el-table-column prop="viewCount" label="浏览" width="80"></el-table-column>
                <el-table-column prop="replyCount" label="回复" width="80"></el-table-column>
                <el-table-column label="操作" width="120" fixed="right">
                  <template #default="scope">
                    <el-button type="primary" size="small" @click="deleteTopic(scope.row.id)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            
            <!-- <el-tab-pane label="账号安全" name="account-security">
              <div class="security-section">
                <div class="security-item">
                  <div class="security-label">登录密码</div>
                  <div class="security-value">******</div>
                  <el-button type="primary" size="small" @click="changePassword">修改</el-button>
                </div>
                <div class="security-item">
                  <div class="security-label">手机绑定</div>
                  <div class="security-value">{{ basicInfoForm.phone || '未绑定' }}</div>
                  <el-button type="primary" size="small" @click="bindPhone">绑定</el-button>
                </div>
                <div class="security-item">
                  <div class="security-label">邮箱绑定</div>
                  <div class="security-value">{{ basicInfoForm.email || '未绑定' }}</div>
                  <el-button type="primary" size="small" @click="bindEmail">绑定</el-button>
                </div>
              </div>
            </el-tab-pane> -->
          </el-tabs>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useGlobalStore } from '../store/userInfo'
import { ElMessage } from 'element-plus'

import {myForum,deleteForum} from '@/request/forum'
import {updateUserInfo} from '@/request/login'

const store = useGlobalStore()

const userInfo = computed(() => store.userInfo)
console.log('userInfo',userInfo.value)
// 用户头像
const userAvatar = ref('https://picsum.photos/id/1005/200/200')
const avatarInput = ref(null)

// 标签页
const activeTab = ref('basic-info')

// 用户等级和积分
const userLevel = ref('Lv.1 旅行新手')
const userPoints = ref(100)

// 基本信息表单
const basicInfoFormRef = ref(null)
const savingBasicInfo = ref(false)

// 基本信息表单验证规则
const basicInfoRules = {
  nickName: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '昵称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  age: [
    { type: 'number', min: 18, max: 65, message: '年龄必须在 18 到 65 之间', trigger: 'blur' }
  ],
  phoneNo: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  bio: [
    { max: 200, message: '个人简介最多 200 个字符', trigger: 'blur' }
  ]
}

// 我的活动数据
const myActivities = ref([
  {
    id: 1,
    name: '周末郊外徒步活动',
    time: '2024-04-15 08:00-16:00',
    location: '郊区国家森林公园',
    status: 'pending',
    statusText: '待审核'
  },
  {
    id: 2,
    name: '春季赏花一日游',
    time: '2024-04-20 07:30-18:00',
    location: '市花卉博览园',
    status: 'participated',
    statusText: '已通过'
  },
  {
    id: 3,
    name: '摄影爱好者交流会',
    time: '2024-03-25 14:00-17:00',
    location: '社团活动室',
    status: 'completed',
    statusText: '已完成'
  },
  {
    id: 4,
    name: '冬季温泉之旅',
    time: '2024-02-10 09:00-18:00',
    location: '温泉度假村',
    status: 'completed',
    statusText: '已完成'
  }
])

// 我的话题数据
const myTopics = ref([])
const getMyTopics = ()=>{
  myForum({
    pageNum: 1,
    pageSize: 10
  }).then(res=>{
    myTopics.value = res.records
  }).catch(err=>{
    console.log(err)
  })
}
getMyTopics();

// 删除话题
const deleteTopic = (id) => {
  deleteForum(id).then(res=>{
    getMyTopics()
    ElMessage({ message: '话题删除成功', type: 'success' })
  }).catch(err=>{
    console.log(err)
  })
}

// 我的回复数量
const myReplies = computed(() => {
  // 实际应用中应该从服务器获取
  return 23
})

// 上传头像
const uploadAvatar = () => {
  avatarInput.value.click()
}

// 处理头像上传
const handleAvatarUpload = (event) => {
  const file = event.target.files[0]
  if (file) {
    // 实际应用中这里应该调用API上传头像
    // 这里简单模拟上传成功
    const reader = new FileReader()
    reader.onload = (e) => {
      userAvatar.value = e.target.result
      ElMessage({ message: '头像上传成功', type: 'success' })
    }
    reader.readAsDataURL(file)
  }
}

// 保存基本信息
const saveBasicInfo = () => {
  basicInfoFormRef.value.validate((valid) => {
    if (valid) {
      savingBasicInfo.value = true
      console.log('userInfo',userInfo.value)
      updateUserInfo(userInfo.value).then(res=>{
        console.log(res)
        store.userInfo = res;
        ElMessage({ message: '基本信息保存成功', type: 'success' })
        savingBasicInfo.value = false
      }).catch(err=>{
        console.log(err)
        savingBasicInfo.value = false
      })
    }
  })
}

// 根据活动状态获取标签类型
const getActivityStatusType = (status) => {
  switch (status) {
    case 'pending':
      return 'warning'
    case 'participated':
      return 'success'
    case 'completed':
      return 'info'
    default:
      return 'info'
  }
}

// 取消活动
const cancelActivity = (id) => {
  // 实际应用中这里应该调用API取消活动
  // 这里简单模拟取消成功
  const activityIndex = myActivities.value.findIndex(item => item.id === id)
  if (activityIndex !== -1) {
    myActivities.value.splice(activityIndex, 1)
    ElMessage({ message: '活动已取消', type: 'success' })
  }
}

// 查看活动详情
const viewActivityDetail = (id) => {
  // 实际应用中这里应该跳转到活动详情页面
  ElMessage({ message: '查看活动详情功能已触发', type: 'success' })
}

// 根据话题分类获取标签类型
const getTopicCategoryType = (category) => {
  const typeMap = {
    1: 'primary',
    2: 'success',
    3: 'warning',
    4: 'danger',
    5: 'info'
  }
  return typeMap[category] || 'info'
}

// 获取话题分类文本
const getTopicCategoryText = (category) => {
  const textMap = {
    1: '旅行攻略',
    2: '线路推荐',
    3: '摄影分享',
    4: '装备讨论',
    5: '结伴同行'
  }
  return textMap[category] || '其他'
}


// 修改密码
const changePassword = () => {
  // 实际应用中这里应该打开修改密码的对话框
  ElMessage({ message: '修改密码功能已触发', type: 'success' })
}

// 绑定手机
const bindPhone = () => {
  // 实际应用中这里应该打开绑定手机的对话框
  ElMessage({ message: '绑定手机功能已触发', type: 'success' })
}

// 绑定邮箱
const bindEmail = () => {
  // 实际应用中这里应该打开绑定邮箱的对话框
  ElMessage({ message: '绑定邮箱功能已触发', type: 'success' })
}

</script>

<style scoped>
.user-center {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-center-content {
  margin-top: 20px;
}

/* 用户基本信息样式 */
.user-info-section {
  display: flex;
  align-items: center;
  padding: 20px;
  background-color: #f5f5f5;
  border-radius: 8px;
  margin-bottom: 30px;
}

.user-avatar {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-right: 30px;
}

.avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  margin-bottom: 10px;
}

.user-basic-info {
  flex: 1;
}

.user-basic-info h3 {
  margin: 0 0 10px 0;
  font-size: 24px;
  color: #333;
}

.user-id,
.user-join-time,
.user-level {
  margin: 5px 0;
  color: #666;
  font-size: 14px;
}

.user-stats {
  display: flex;
  gap: 30px;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #1890ff;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

/* 个人信息编辑样式 */
.user-edit-section {
  margin-top: 20px;
}

/* 账号安全样式 */
.security-section {
  margin-top: 20px;
}

.security-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
}

.security-item:last-child {
  border-bottom: none;
}

.security-label {
  font-size: 16px;
  color: #333;
}

.security-value {
  font-size: 14px;
  color: #666;
}

/* 话题标题样式 */
.topic-title {
  color: #333;
  text-decoration: none;
}

.topic-title:hover {
  color: #1890ff;
}
</style>